<template>
	<view class="content">
		<image class="logo" src="/static/jenkins.svg"></image>
		<view v-if="need_login" class="uni-common-mt">
			<view class="uni-flex uni-row">
				<view class="uni-form-item">
					<view class="title">账户</view>
					<input class="uni-input" v-model="username" />
				</view>
			</view>
			<view class="uni-flex uni-row">
				<view class="uni-form-item">
					<view class="title">密码</view>
					<input password="true" class="uni-input" v-model="password" />
				</view>
			</view>
			<view class="uni-card">
				<button type="primary" @click="onSubmit">登录</button>
			</view>
		</view>
		<view v-else class="uni-badge-yellow">
			欢迎 {{ name }} 大驾光临
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: '请登录',
				username: '',
				password: '',
				name: '',
				token: '',
				need_login: true
			}
		},
		onLoad() {
			var _this = this;
			var token_obj = this.common.getToken()
			if (token_obj != null) {
				this.token = token_obj.token
				this.username = token_obj.username
				this.need_login = false
				this.name = token_obj.name
			}
		},
		onShow() {
			var token_obj = this.common.getToken()
			if (token_obj == null) {
				this.need_login = true
			}
		},
		methods: {
			onSubmit() {
				uni.clearStorage();
				if (this.username == null || this.username.length < 3) {
					uni.showToast({
						icon: "none",
						title: "账户格式错误"
					})
					return false;
				}
				if (this.password.length < 6) {
					uni.showToast({
						icon: "none",
						title: "密码格式错误"
					})
					return false;
				}
				var _this = this;
				this.common.requestAPI(this.common.config.API_LOGIN, 'POST', {
					username: this.username,
					password: this.password
				}, '正在登录', function(res) {
					if (res.status == 'OK') {
						uni.setStorage({
							key: 'LOGIN_TOKEN',
							data: {
								username: res.result.username,
								user_id: res.result.user_id,
								name: res.result.name,
								token: res.result.token,
								is_admin: res.result.is_admin
							},
							success: function(e) {
								uni.showToast({
									title: '登录成功'
								});
								_this.name = res.result.name
								_this.need_login = false
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						});
					}
				})
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 240rpx;
		width: 174rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
